package com.ruoyi.epidemic.handler;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.epidemic.domain.SysUserDept;
import com.ruoyi.epidemic.domain.WxCpSysDept;
import com.ruoyi.epidemic.domain.WxCpSysUser;
import com.ruoyi.epidemic.mapper.*;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpDepartmentService;
import me.chanjar.weixin.cp.api.impl.WxCpDepartmentServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpUserServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wf
 * @date 2022年04月04日
 */
@Component
public class ContactsSyncHandler {

    @Value("${wechat.cp.corpId}")
    private String corpId;

    @Value("${wechat.cp.appConfigs.agentId}")
    private Integer agentId;

    @Value("${wechat.cp.appConfigs.secret}")
    private String secret;

    @Value("${wechat.cp.appConfigs.token}")
    private String token;

    @Value("${wechat.cp.appConfigs.aesKey}")
    private String aesKey;

    @Autowired
    private SysUserDeptMapper sysUserDeptMapper;

    @Autowired
    private WxCpUserMapper wxCpUserMapper;

    @Autowired
    private WxCpDepartMapper wxCpDepartMapper;

    @Autowired
    private WxCpSysUserMapper wxCpSysUserMapper;

    @Autowired
    private WxCpSysDeptMapper wxCpSysDeptMapper;


    public List<WxCpDepart> getDepartmentList() throws WxErrorException {
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setCorpId(corpId);      // 设置微信企业号的appid
        config.setCorpSecret(secret);  // 设置微信企业号的app corpSecret

        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);

        WxCpDepartmentService wxCpDepartmentService = new WxCpDepartmentServiceImpl(wxCpService);

        List<WxCpDepart> departList =  wxCpDepartmentService.list(null);
        System.out.println(departList);
        return departList;
    }

    public List<WxCpUser> getUserList(List<WxCpDepart> departList) throws WxErrorException {
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setCorpId(corpId);      // 设置微信企业号的appid
        config.setCorpSecret(secret);  // 设置微信企业号的app corpSecret

        List<WxCpDepart> companys = departList.stream().filter(d -> d.getParentId() == 0).collect(Collectors.toList());

        WxCpDepart company = companys.get(0);

        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);

        WxCpUserServiceImpl wxCpUserService = new WxCpUserServiceImpl(wxCpService);

        List<WxCpUser> userList =  wxCpUserService.listSimpleByDepartment(company.getId(),true, 0);
        System.out.println(userList);
        return userList;
    }

    @Transactional(rollbackFor = Exception.class)
    public void sync () throws WxErrorException {

        List<com.ruoyi.epidemic.domain.WxCpDepart> wxDepartInsertList = new ArrayList<com.ruoyi.epidemic.domain.WxCpDepart>();
        List<WxCpSysDept> departInsertList = new ArrayList<WxCpSysDept>();
        List<com.ruoyi.epidemic.domain.WxCpUser> wxUserInsertList = new ArrayList<>();
        List<WxCpSysUser> userInsertList = new ArrayList<WxCpSysUser>();
        List<SysUserDept> userDeptInsertList = new ArrayList<SysUserDept>();

        List<WxCpDepart> departList = this.getDepartmentList();
        List<WxCpUser> userList = this.getUserList(departList);

        Date createTime = new Date();

        for(WxCpDepart depart : departList){

            //保存企业微信部门信息
            com.ruoyi.epidemic.domain.WxCpDepart wxCpDepart = new com.ruoyi.epidemic.domain.WxCpDepart();
            wxCpDepart.setDeptId(depart.getId());
            wxCpDepart.setParentId(depart.getParentId());
            wxCpDepart.setDeptName(depart.getName());
            wxCpDepart.setOrderNum(depart.getOrder());
            wxCpDepart.setDelFlag("0");
            wxCpDepart.setCreateTime(createTime);
            wxDepartInsertList.add(wxCpDepart);

            //保存部门信息
            WxCpSysDept sysDept = new WxCpSysDept();
            sysDept.setDeptId(depart.getId());
            sysDept.setParentId(depart.getParentId());
            sysDept.setDeptName(depart.getName());
            sysDept.setOrderNum(depart.getOrder());
            sysDept.setDelFlag("0");
            sysDept.setCreateTime(createTime);
            departInsertList.add(sysDept);
        }

        for(WxCpUser user : userList){

            String userId = user.getUserId();
            Long[] departIds = user.getDepartIds();
            String name = user.getName();

            com.ruoyi.epidemic.domain.WxCpUser wxCpUser = new com.ruoyi.epidemic.domain.WxCpUser();
            //保存企业微信员工信息
            wxCpUser.setUserId(userId);
            wxCpUser.setDeptIds(JSONUtil.toJsonStr(departIds));
            wxCpUser.setLoginName(name);
            wxCpUser.setUserName(name);
            wxCpUser.setDelFlag("0");
            wxCpUser.setCreateTime(createTime);
            wxUserInsertList.add(wxCpUser);

            //保存员工信息
            WxCpSysUser sysUser = new WxCpSysUser();
            sysUser.setUserId(userId);
            sysUser.setLoginName(name);
            sysUser.setUserName(name);
            sysUser.setDelFlag("0");
            sysUser.setCreateTime(createTime);
            wxCpSysUserMapper.insertWxCpSysUser(sysUser);
//            userInsertList.add(sysUser);

            //保存员工-部门关系信息
            for(Long departId : departIds){
                SysUserDept sysUserDept = new SysUserDept();
                sysUserDept.setUserId(userId);
                sysUserDept.setDeptId(departId);
                sysUserDept.setCreateTime(createTime);
                sysUserDeptMapper.insertSysUserDept(sysUserDept);
            }
        }

        wxCpUserMapper.batchReplace(wxUserInsertList);
        wxCpDepartMapper.batchReplace(wxDepartInsertList);
        wxCpSysDeptMapper.batchReplace(departInsertList);
//        sysUserMapper.batchReplace(userInsertList);
//        wxCpSysUserMapper.batchInsert(userInsertList);
    }


}
